package com.gblw.rjkf.pj.service.impl;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblw.rjkf.pj.entity.SysMenus;
import com.gblw.rjkf.pj.entity.SysPermissions;
import com.gblw.rjkf.pj.entity.SysRole;
import com.gblw.rjkf.pj.mapper.SysMenusMapper;
import com.gblw.rjkf.pj.mapper.SysPermissionsMapper;
import com.gblw.rjkf.pj.mapper.SysRoleMapper;
import com.gblw.rjkf.pj.service.SysRoleService;
import com.gblw.rjkf.pj.utils.OtherUtils;
import com.gblw.rjkf.pj.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SysRoleServiceImpl(SysRole)
 *
 * @author wj
 * @since 2024-09-20 19:18:09
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Override
    public Result page(Integer pageNum, Integer pageSize, String name) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        // 判断 name 是否有值，如果有值则添加到查询条件中
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }
        Page<SysRole> page = new Page<>(pageNum, pageSize);
        IPage<SysRole> pageList = baseMapper.selectPage(page, queryWrapper);
        return Result.success("查询成功", pageList);
    }

    @Override
    public Result insert(SysRole sysRole) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", sysRole.getName());
        List<SysRole> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            baseMapper.insert(sysRole);
            return Result.success("添加成功", "");
        }
        return Result.error("角色已经存在");
    }


    @Override
    public Result update(SysRole sysRole) {

        // 获取当前要更新的记录的 ID
        Integer currentId = sysRole.getId();

        // 创建查询包装器
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();

        // 构建 OR 条件：name 或 code 任意一个存在，并且排除当前记录的 ID
        queryWrapper.or(orWrapper -> {
            orWrapper.eq("name", sysRole.getName());
        }).ne(currentId != null, "id", currentId);

        // 执行查询
        List<SysRole> list = baseMapper.selectList(queryWrapper);

        // 检查是否存在
        if (!list.isEmpty()) {
            return Result.error("角色已存在，请检查");
        } else {
            // 更新记录
            baseMapper.updateById(sysRole);
            return Result.success("更新成功", "");
        }
    }


    @Resource
    private SysMenusMapper sysMenusMapper;

    @Override
    public Result buildMenuTree() {
        // 获取所有菜单
        List<SysMenus> allMenus = sysMenusMapper.getAllMenus();

        // 创建一个映射，用于快速查找子菜单
        Map<Integer, SysMenus> menuById = allMenus.stream()
                .collect(Collectors.toMap(SysMenus::getId, menuItem -> menuItem));
        List<Map<String, Object>> menu = new ArrayList<>();
        for (SysMenus sysMenu : allMenus) {
            if (sysMenu.getParentId() == null) { // 只处理顶级菜单
                Map<String, Object> menuMap = new HashMap<>();
                menuMap.put("id", sysMenu.getId());
                // 检查顶级菜单是否有子菜单
                menuMap.put("name", sysMenu.getText());
                List<Map<String, Object>> children = buildChildren(sysMenu.getId(), allMenus, menuById);
                if (!children.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    menuMap.put("children", children);
                }
                menu.add(menuMap);
            }
        }

        return Result.success("查询成功", menu);
    }

    private List<Map<String, Object>> buildChildren(int parentId, List<SysMenus> allMenus, Map<Integer, SysMenus> menuById) {
        List<Map<String, Object>> children = new ArrayList<>();
        for (SysMenus sysPermissions : allMenus) {
            if (sysPermissions.getParentId() != null && sysPermissions.getParentId().equals(parentId)) {
                Map<String, Object> childMap = new HashMap<>();
                childMap.put("id", sysPermissions.getId());
                childMap.put("name", sysPermissions.getText()); // 子菜单包含 name 字段
                childMap.put("parentId", sysPermissions.getParentId());
                // 递归构建子菜单
                List<Map<String, Object>> subChildren = buildChildren(sysPermissions.getId(), allMenus, menuById);
                if (!subChildren.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    childMap.put("children", subChildren);
                }
                children.add(childMap);
            }
        }
        return children;
    }

    @Resource
    SysPermissionsMapper sysPermissionsMapper;

    public List<String> cachedPermissions() {

        // 1. 声明权限码集合
        List<String> permissionList = new ArrayList<>();
        Long id = (Long) StpUtil.getLoginId();
        SysRole sysRole = sysMenusMapper.getRoleById(Integer.parseInt(StpUtil.getLoginId().toString()));

        List<String> cachedPermissions = (List<String>) SaManager.getSaTokenDao().getObject("satoken:role-find-permission:" + id);
        if (cachedPermissions == null) {
            QueryWrapper<SysPermissions> queryWrapper = new QueryWrapper<>();

            queryWrapper.in("id", OtherUtils.castInteger(sysRole.getPremisIds())); // 假设SysPermissions实体中有个字段叫role_id关联到角色
            List<SysPermissions> permissions = sysPermissionsMapper.selectList(queryWrapper);
            if (permissions != null && permissions.size() > 0) {
                // 转换为权限码列表
                List<String> permissionsCodes = permissions.stream()
                        .map(SysPermissions::getCode)
                        .collect(Collectors.toList());

                // 查好后，设置到缓存中
                SaManager.getSaTokenDao().setObject("satoken:role-find-permission:" + id, permissionsCodes, 60 * 60 * 24 * 30);
                cachedPermissions = permissionsCodes;
            }

        }
        permissionList.addAll(cachedPermissions);
        // 4. 返回权限码集合
        return permissionList;
    }



    public List<String> getRoleList() {
        SysRole sysRole = sysMenusMapper.getRoleById(Integer.parseInt(StpUtil.getLoginId().toString()));
        Long id = (Long) StpUtil.getLoginId();
        List<String> roleList = (List<String>) SaManager.getSaTokenDao().getObject("satoken:loginId-find-role:" + id);
        if (roleList == null) {
            // 从数据库查询这个账号id拥有的角色列表，
            roleList = OtherUtils.castString(sysRole.getName().toString());
            // 查好后，set 到缓存中
            SaManager.getSaTokenDao().setObject("satoken:loginId-find-role:" + id, roleList, 60 * 60 * 24 * 30);
        }
        System.err.println(roleList);
        return roleList;
    }
}